package com.x.Part4_同步方法处理线程安全;

/**
 * ClassName: WindowTest
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.03.27 14:58
 */
public class WindowTest_Runnable {
    public static void main(String[] args) {

        Window window = new Window();

        new Thread(window).start();
        new Thread(window).start();
        new Thread(window).start();

    }
}

class Window implements Runnable{
    int ticket = 1000;

    Object o = new Object();

    @Override
    public void run() {
        while (true){

                //更换为show()方法
                /*if(ticket>0){
                    System.out.println(Thread.currentThread().getName()+"票号为：" + ticket);
                    ticket--;
                }else
                    break;*/
            show();
        }
    }

    public synchronized void show(){//此方法的同步监视器为this，由于Window类的实例唯一，所以this唯一，所以线程安全
        if(ticket>0){
            System.out.println(Thread.currentThread().getName()+"票号为：" + ticket);
            ticket--;
        }
    }
}


